#coding:utf-8
import socket
import sys

import json
import struct
import time
import random

from twisted.internet import protocol,reactor,task,defer,threads

def encodePacket(optId,body,flag = 1):
    dataTmp={}
    dataTmp['protocol']=str(optId)
    dataTmp['body']=body
    jsonTmp=json.dumps(dataTmp)
    jsonSizeTmp=len(jsonTmp)
    fmt="!I%ss"%jsonSizeTmp
    return struct.pack(fmt,jsonSizeTmp,jsonTmp)



sockIndex = 1


def connToServer ():
    global sockIndex

    print sockIndex
    #创建一个socket连接到127.0.0.1:5200，并发送内容
    time.sleep(0.3)

    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    conn.connect(("127.0.0.1", 8880))

    sockIndex = sockIndex + 1


    #模拟登录
    sendData = encodePacket(40001,{"playerId":123})
    conn.send(sendData)

    while True:
        #等待服务端返回数据，并输出
        rev = conn.recv(1024)
        print 'get server msg:' + str(rev)
        # stackless.schedule()

    #stackless.schedule()

# for i in range(0,1):
#     stackless.tasklet(connToServer)()


# stackless.run()
if __name__ == '__main__':
    connToServer()